package com.zlt.controller;


import com.alibaba.fastjson.JSONObject;
import com.zlt.dto.UserDTO;
import com.zlt.entity.User;
import com.zlt.service.UserService;
import com.zlt.service.impl.UserServiceImpl;
import com.zlt.util.*;
import com.zlt.util.CodeUtil.CodeUtil;
import com.zlt.vo.ActiveUser;
import com.zlt.vo.Result;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author wbh
 * @version 1.0
 * @description: TODO
 * @date 2022/8/10 19:40
 */
@WebServlet(name = "UserController", value = "/user/*")
public class UserController extends BaseController {

    private UserService userService = new UserServiceImpl();

    @Override
    protected void defaultMethod(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    /**
     * 通过邮箱进行密码的更新
     *
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    protected Result updatePasswordEmail(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        UserDTO userDto = ClassUtil.resolveRequest(UserDTO.class, req);

        //邮箱验证
        boolean validEmail = RegularUtil.isValidEmail(userDto.getEmail());
        System.out.println("validEmail:" + validEmail);
        if (!validEmail) {
            return Result.error("邮箱格式错误");
        }

        //校验验证码
        String emailCode = userDto.getEmailCode();
        Jedis connection = JedisUtil.getConnection();
        String s = connection.get("emailCode");

        if (!StringUtil.isNotNull(s)) {
            return Result.error("验证码过期");

        }

        if (!s.equalsIgnoreCase(emailCode)) {
            return Result.error("验证码错误");
        }

        if (userDto != null) {
            try {
                boolean success = userService.modifyByEmail(userDto);
                System.out.println("userService.reg:" + success);
                return success ? Result.ok("修改成功") : Result.error("修改失败");
            } catch (RuntimeException e) {
                e.printStackTrace();
                return Result.error("修改失败");
            }
        }
        return Result.error("修改失败");

    }


    /**
     * 忘记密码   通过邮箱验证
     *
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    protected Result userForgetEmailCode(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        UserDTO userDto = ClassUtil.resolveRequest(UserDTO.class, req);

        System.out.println("userReg:" + userDto);

        //邮箱验证
        boolean validEmail = RegularUtil.isValidEmail(userDto.getEmail());
        System.out.println("validEmail:" + validEmail);
        if (!validEmail) {
            return Result.error("邮箱格式错误");
        }

        String emailCode = CodeUtil.sendEmail(userDto.getEmail());


        Jedis connection = JedisUtil.getConnection();
        String s = connection.setex("emailCode", 300, emailCode);
        connection.close();

        return Result.ok("发送成功", s);

    }



    /**
     * 通过手机号 进行密码的重置
     *
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    protected Result updatePassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        UserDTO userDto = ClassUtil.resolveRequest(UserDTO.class, req);

        //手机号码验证
        boolean validPhoneNumber = RegularUtil.isValidPhoneNumber(userDto.getUsername());
        System.out.println("validPhoneNumber:" + validPhoneNumber);
        if (!validPhoneNumber) {
            return Result.error("手机号不正确");
        }

        //校验验证码
        String PhoneCode = userDto.getPhoneCode();
        Jedis connection = JedisUtil.getConnection();
        String s = connection.get("phoneCode");

        if (!StringUtil.isNotNull(s)) {
            return Result.error("验证码过期");

        }

        if (!s.equalsIgnoreCase(PhoneCode)) {
            return Result.error("验证码错误");
        }

        if (userDto != null) {
            try {
                boolean success = userService.modify(userDto);
                System.out.println("userService.reg:" + success);
                return success ? Result.ok("修改成功") : Result.error("修改失败");
            } catch (RuntimeException e) {
                e.printStackTrace();
                return Result.error("修改失败");
            }
        }
        return Result.error("修改失败");

    }

    /**
     * 使用手机号码登录
     *
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    protected Result userPhoneLogin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        UserDTO userDto = ClassUtil.resolveRequest(UserDTO.class, req);

        if (userDto != null) {

            //手机号码验证
            boolean validPhoneNumber = RegularUtil.isValidPhoneNumber(userDto.getUsername());
            System.out.println("validPhoneNumber:" + validPhoneNumber);
            if (!validPhoneNumber) {
                return Result.error("手机号码不正确");
            }

            //校验验证码
            String PhoneCode = userDto.getPhoneCode();
            Jedis connection = JedisUtil.getConnection();
            String s = connection.get("phoneCode");

            if (!StringUtil.isNotNull(s)) {
                return Result.error("验证码过期");

            }

            if (!s.equalsIgnoreCase(PhoneCode)) {
                return Result.error("验证码错误");
            }

            try {
                String token = userService.login(userDto);
                resp.setHeader("token", token);
                //User user = userService.loginDo(userDto);
                //req.getSession().setAttribute("CUR_USER",user);

                return Result.ok("登录成功");
            } catch (RuntimeException e) {
                e.printStackTrace();
                return Result.error(e.getMessage());
            }
        }

        return Result.error("登录失败");
    }

    /**
     * 忘记密码---获取手机验证码
     *
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    protected Result userForgetPhoneCode(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        UserDTO userDto = ClassUtil.resolveRequest(UserDTO.class, req);

        System.out.println("userReg:" + userDto);

        //手机号码验证
        boolean validPhoneNumber = RegularUtil.isValidPhoneNumber(userDto.getUsername());
        System.out.println("validPhoneNumber:" + validPhoneNumber);
        if (!validPhoneNumber) {
            return Result.error("手机号不正确");
        }

        String phoneCode = CodeUtil.modifyPhoneCode(userDto.getUsername());
        JSONObject object = JSONObject.parseObject(phoneCode);
        System.out.println("objects:" + object);

        JSONObject params = object.getJSONObject("params");
        System.out.println("params:" + params);

        String code = (String) params.get("code");
        System.out.println("code:" + code);

        Jedis connection = JedisUtil.getConnection();
        String s = connection.setex("phoneCode", 300, code);
        connection.close();

        return Result.ok("发送成功", s);
    }

    /**
     * 获取登录手机验证码
     *
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    protected Result userLoginPhoneCode(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        UserDTO userDto = ClassUtil.resolveRequest(UserDTO.class, req);

        System.out.println("userReg:" + userDto);

        //手机号码验证
        boolean validPhoneNumber = RegularUtil.isValidPhoneNumber(userDto.getUsername());
        System.out.println("validPhoneNumber:" + validPhoneNumber);
        if (!validPhoneNumber) {
            return Result.error("手机号不正确");
        }

        String phoneCode = CodeUtil.logPhoneCode(userDto.getUsername());
        JSONObject object = JSONObject.parseObject(phoneCode);
        System.out.println("objects:" + object);

        JSONObject params = object.getJSONObject("params");
        System.out.println("params:" + params);

        String code = (String) params.get("code");
        System.out.println("code:" + code);

        Jedis connection = JedisUtil.getConnection();
        String s = connection.setex("phoneCode", 300, code);
        connection.close();

        return Result.ok("发送成功", s);
    }


    /**
     * 获取注册手机验证码
     *
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    protected Result userRegPhoneCode(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        UserDTO userDto = ClassUtil.resolveRequest(UserDTO.class, req);

        System.out.println("userReg:" + userDto);

        //手机号码验证
        boolean validPhoneNumber = RegularUtil.isValidPhoneNumber(userDto.getUsername());
        System.out.println("validPhoneNumber:" + validPhoneNumber);
        if (!validPhoneNumber) {
            return Result.error("手机号不正确");
        }

        String phoneCode = CodeUtil.regPhoneCode(userDto.getUsername());
        JSONObject object = JSONObject.parseObject(phoneCode);
        System.out.println("objects:" + object);

        JSONObject params = object.getJSONObject("params");
        System.out.println("params:" + params);

        String code = (String) params.get("code");
        System.out.println("code:" + code);

        Jedis connection = JedisUtil.getConnection();
        String s = connection.setex("phoneCode", 300, code);
        connection.close();

        return Result.ok("发送成功", s);
    }


    /**
     * 查询当前用户的信息
     *
     * @param request
     * @param response
     */
    protected Result infoUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        ActiveUser activeUser = ActiveUserUtil.get();
        User user = userService.selectUserByUsername(activeUser.getUsername());
        System.out.println("---------jjj" + user);
        if (activeUser == null && user == null) {
            return Result.error("查询失败");
        }
        return Result.ok("查询成功", user);

    }


    /**
     * 查询当前用户的信息
     *
     * @param req
     * @param resp
     */
    protected Result info(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        return Result.ok("", ActiveUserUtil.get());
    }

    /**
     * 修改招聘用户的信息
     *
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
//    protected Result info(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
///*
//        return Result.ok("", ActiveUserUtil.get());*/


    protected Result updateRecruit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        UserDTO userDTO = ClassUtil.resolveRequest(UserDTO.class, request);
        userDTO.setPhoto(userDTO.getFile());
        System.out.println(userDTO);

        userService.updateRecruit(userDTO);

        return Result.ok("查询成功", userDTO);

    }

    /**
     * 用户登录
     *
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    protected Result userLogin(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        UserDTO userDto = ClassUtil.resolveRequest(UserDTO.class, req);

        if (userDto != null) {

            //手机号码验证
            boolean validPhoneNumber = RegularUtil.isValidPhoneNumber(userDto.getUsername());
            System.out.println("validPhoneNumber:" + validPhoneNumber);
            if (!validPhoneNumber) {
                return Result.error("手机号码不正确");
            }

            //数据校验
            String key = req.getHeader("token");
            Jedis connection = JedisUtil.getConnection();
            String s = connection.get(key);

            if (!StringUtil.isNotNull(s)) {
                return Result.error("验证码过期");

            }


            if (!s.equalsIgnoreCase(userDto.getCode())) {
                return Result.error("验证码错误");
            }

            try {
                String token = userService.login(userDto);
                resp.setHeader("token", token);
                return Result.ok("登录成功");
            } catch (RuntimeException e) {
                e.printStackTrace();
                return Result.error(e.getMessage());
            }
        }

        return Result.error("登录失败");
    }

    /**
     * 用户注册
     *
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    protected Result userReg(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        UserDTO userDto = ClassUtil.resolveRequest(UserDTO.class, req);
        System.out.println("userReg:" + userDto);

        //手机号码验证
        boolean validPhoneNumber = RegularUtil.isValidPhoneNumber(userDto.getUsername());
        System.out.println("validPhoneNumber:" + validPhoneNumber);
        if (!validPhoneNumber) {
            return Result.error("手机号不正确");
        }

        //邮箱验证
        boolean validEmail = RegularUtil.isValidEmail(userDto.getEmail());
        System.out.println("validEmail:" + validEmail);
        if (!validEmail) {
            return Result.error("邮箱格式错误");
        }

        //校验验证码
        String PhoneCode = userDto.getPhoneCode();
        Jedis connection = JedisUtil.getConnection();
        String s = connection.get("phoneCode");

        if (!StringUtil.isNotNull(s)) {
            return Result.error("验证码过期");

        }

        if (!s.equalsIgnoreCase(PhoneCode)) {
            return Result.error("验证码错误");
        }


        if (userDto != null) {
            try {
                boolean success = userService.reg(userDto);
                System.out.println("userService.reg:" + success);
                return success ? Result.ok("注册成功") : Result.error("注册失败");
            } catch (RuntimeException e) {
                e.printStackTrace();
                return Result.error("注册失败");
            }
        }
        return Result.error("注册失败");
    }

    /**
     * 获取图片验证码
     *
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    protected Result vailCode(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //创建图片
        BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
        //获取画笔
        Graphics2D graphics2D = image.createGraphics();
        //绘制背景颜色
        int br = (int) (Math.random() * 128);
        int bg = (int) (Math.random() * 128);
        int bb = (int) (Math.random() * 128);
        //设置画笔颜色
        graphics2D.setColor(new Color(br, bg, bb));

        //绘制一个矩形
        graphics2D.fillRect(0, 0, 80, 20);
        //设置验证码显示的颜色
        int fr = (int) (Math.random() * 128) + 128;
        int fg = (int) (Math.random() * 128) + 128;
        int fb = (int) (Math.random() * 128) + 128;
        //设置画笔颜色
        graphics2D.setColor(new Color(fr, fg, fb));

        //获取验证码的文字
        String s = StringUtil.randomStr(4);
        System.out.println(s);

        //放入redis中
        Jedis connection = JedisUtil.getConnection();
        String key = StringUtil.uuid();
        connection.setex(key, 300, s);
        connection.close();

        resp.setHeader("token", key);

        graphics2D.setFont(new Font("黑体", Font.PLAIN, 18));
        graphics2D.drawString(s, 5, 18);
        //销毁画笔
        graphics2D.dispose();
        return Result.ok("", StringUtil.changeImageToString(image));
    }


    /**
     * 通过username找user
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected Result selectUserByUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String username = req.getParameter("username");
        System.out.println("username===" + username);

        try {
            User user = userService.selectUserByUsername(username);
            if (user != null) {
                return Result.ok("√");
            }
            return Result.error("当前号码未绑定");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.ok(e.getMessage());
        }

    }
}
